package edu.chl.da.ejb.ctrl;

import edu.chl.da.ejb.core.Airplane;
import edu.chl.da.ejb.core.Seat;
import edu.chl.da.ejb.core.SeatPK;
import edu.chl.da.ejb.persistency.IAirplaneFacade;
import edu.chl.da.ejb.persistency.ISeatFacade;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;

/**
 *
 * @author Max
 */
@Stateless
public class ManageAirplane implements IManageAirplane {

    @EJB
    IAirplaneFacade iaf;

    @EJB
    ISeatFacade isf;
    
    @Override
    public Airplane createAirplane(String model) {
        List<Seat> seatList = new ArrayList<Seat>();

        Airplane airplane = new Airplane();
        airplane.setModel(model);
        airplane.setSeatList(seatList);
        airplane = iaf.create(airplane);

        return airplane;
    }

    @Override
    public void createSeatsForAirplane(Airplane a) {
        List<Seat> seatList = new ArrayList<Seat>();
        for(int i=0; i < 10; i++){
            SeatPK seatPK = new SeatPK();
            seatPK.setAirplane(a.getId());
            seatPK.setRow(1);
            seatPK.setSeatno(i+1);

            Seat seat = new Seat();
            seat.setAirplane1(a);
            seat.setSeatPK(seatPK);

            isf.create(seat);
            seatList.add(seat);
        }
        // Adds the seat list to airplane
        iaf.edit(a);
    }


    @Override
    public Airplane editAirplane(Airplane airplane) {
        if(airplane == null){
            throw new NullPointerException("Airplane is null");
        }
        iaf.edit(airplane);
        return airplane;
    }

    @Override
    public boolean removeAirplane(Airplane airplane) {
        try {
        iaf.remove(airplane);
        }
        catch(Exception e){
            return false;
        }
        return true;
    }

    @Override
    public Seat addSeat(Airplane airplane, Seat seat) {
        List<Seat> seatList = airplane.getSeatList();
        seatList.add(seat);
        seat.setAirplane1(airplane);
        airplane.setSeatList(seatList);
        isf.create(seat);
        iaf.edit(airplane);
        return seat;
    }

    @Override
    public boolean removeSeat(Seat seat) {
        try{
            isf.remove(seat);
        }
        catch(Exception e){
            return false;
        }
        return true;
    }

    @Override
    public List<Seat> getSeatList(Airplane airplane) {
        return iaf.find(airplane).getSeatList();
    }

    @Override
    public Airplane getAirplaneByID(Integer id) {
        return iaf.find(id);
    }

    @Override
    public List<Airplane> getAllAirplanes() {
        return iaf.findAll();
    }
}
